require 'erb'
require 'common/base'

# globally map transports to tag variable parsed from receive messages
$to_tags = Hash.new

class SIPBase < Base

  attr_accessor :step, :transport, :base_options, :base_transports, :base_variables, :message, :domain, :sender, :recipient, :recipient_2, :branch, :from_tag, :to_tag, :call_id

  def initialize(step, filename, params = {}, transport="SIP")
    super()
    @transport = transport
    @step = step
    
    @domain = params["domain"] or ""
    @sender = params["sender"] or ""
    @recipient = params["recipient"] or ""
    @recipient_2 = params["recipient_2"] or ""
    @branch = new_branch
    @from_tag = new_tag    
    @call_id = new_call_id



    @base_options = "
     $domain='<%= @domain %>'
     $sender='<%= @sender %>'
     $recipient='<%= @recipient %>'
     $recipient_2='<%= @recipient_2 %>'"

    @base_variables = ''

    @base_transports = 'SIP = udp(src_port: 5060, dst_port: 5060)
    SIP_2 = udp(src_port: 5060, dst_port: 5060)'

    if !filename.nil?
      template = get_message("SIP", filename)
      erb = ERB.new(template, 0, '%<>')
      @message = erb.result(binding)

      # save captured variable
      if template.include?("@to_tag =")
        set_tag_call("SIP_Client_Receive_#{@step}", @transport)
      end
    end
  end

  # only set the to_tag one time, the first time
  def set_tag_call(tag, transport)
     $to_tags[transport] = tag
  end

  def get_tag_call(transport)
     return $to_tags[transport]
  end

  def new_call_id
    return "#{rand_alphanumeric}@#{@domain}"
  end

  def new_branch
    return "z9hG4bK#{rand_alphanumeric}"
  end

  def new_tag
    return rand_alphanumeric
  end

  def rand_alphanumeric(size=8)
    s = ""
    size.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
    s
  end

end
